<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue.js Video Player with Audio Control</title>
    <style>
        .container {
            display: flex;
            flex-wrap: wrap;
            width: 750px;
            height: 500px;
            position: relative;
        }
        .video-box {
            border: 1px solid #000;
            box-sizing: border-box;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 33.33%;
            height: 50%;
            position: relative;
        }
        .expanded {
            width: 70%;
            height: 100%;
            position: absolute;
            left: 0;
            top: 0;
            z-index: 2;
        }
        .collapsed {
            width: 30%;
            height: 20%;
            position: absolute;
            right: 0;
            z-index: 1;
        }
        .controls {
            margin-top: 10px;
        }

        button {
            margin-right: 5px;
        }

    </style>
</head>
<body>
<div id="app">
    <div class="controls">
        <button @click="selectDirectory">选择目录</button>
        <button @click="fastForward">快进1帧</button>
        <button @click="rewind">退回1帧</button>
        <button @click="pauseAll">暂停所有</button>
        <button @click="playAll">播放所有</button>
        <button @click="clearVideos">清空所有视频</button>
        <input type="file" webkitdirectory directory multiple @change="handleDirectorySelected" style="display: none;" ref="directoryInput">

        <input type="text" id="convertDirectoryPath" v-model="convertDirectoryPath" placeholder="输入绝对路径" />
        <button @click="sendConvertDirectoryPath">转换格式</button>
    </div>
    <div class="container">
        <video v-for="index in 6" :key="index" :class="{'expanded': activeIndex === index, 'collapsed': activeIndex !== -1 && activeIndex !== index}" :style="collapsedStyle(index)" @click.stop.prevent="toggleBox(index, $event)" class="video-box" :src="videoPaths[index-1]" controls>
        </video>
        <!-- 添加音频元素，设置为隐藏 -->
        <audio ref="audioPlayer" :src="audioPath" style="display: none;"></audio>
    </div>
</div>
<script src="public/js/vue.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            activeIndex: -1,
            convertDirectoryPath: '', // 用于存储用户输入的绝对路径
            videoPaths: [], // 存储视频文件路径
            audioPath: '' // 存储音频文件路径
        },
        methods: {
            toggleBox(index, event) {
                // 阻止默认行为，例如播放或暂停视频
                event.preventDefault();

                // 获取点击的视频元素
                const video = this.$el.querySelectorAll('video')[index - 1];
                // 检查视频是否正在播放
                const isPlaying = !video.paused && !video.ended && video.readyState > 2;

                // 切换activeIndex来改变视频的展开/折叠状态
                this.activeIndex = this.activeIndex === index ? -1 : index;

                // 如果视频在点击之前正在播放，则保持播放状态
                if (isPlaying) {
                    this.$nextTick(() => {
                        video.play().catch(error => {
                            // 处理浏览器不允许自动播放的情况
                            console.error("Play failed:", error);
                        });
                    });
                }
            },
            collapsedStyle(index) {
                if (this.activeIndex !== -1 && this.activeIndex !== index) {
                    const collapsedHeight = 500 * 0.2;
                    let adjustedIndex = index - 1;
                    if (index > this.activeIndex) {
                        adjustedIndex--; // Move the index up by one for boxes after the active one
                    }
                    const topPosition = adjustedIndex * collapsedHeight;
                    return {
                        top: `${topPosition}px`
                    };
                }
                return {};
            },
            fastForward() {
                const frameTime = 1 / 25; // 1 frame at 25 fps
                const videos = this.$el.querySelectorAll('video');
                videos.forEach(video => {
                    video.currentTime = Math.min(video.currentTime + frameTime, video.duration);
                });
            },
            rewind() {
                const frameTime = 1 / 25;
                const videos = this.$el.querySelectorAll('video');
                videos.forEach(video => {
                    video.currentTime = Math.max(video.currentTime - frameTime, 0);
                });
            },
            pauseAll() {
                const videos = this.$el.querySelectorAll('video');
                const audio = this.$refs.audioPlayer;
                videos.forEach(video => {
                    video.pause();
                });
                if (audio) {
                    audio.pause();
                }
            },
            playAll() {
                const videos = this.$el.querySelectorAll('video');
                const audio = this.$refs.audioPlayer;
                videos.forEach(video => {
                    video.play();
                });
                if (audio) {
                    audio.play();
                }
            },
            clearVideos() {
                // 清空视频路径数组
                this.videoPaths = [];
                // 重置activeIndex
                this.activeIndex = -1;
                // 查找所有video元素并移除src属性
                const videos = this.$el.querySelectorAll('video');
                videos.forEach(video => {
                    video.src = '';
                    video.load(); // 重新加载视频元素，以清除播放器状态
                });
                // 清空音频路径
                this.audioPath = '';
                // 重置音频播放器
                const audio = this.$refs.audioPlayer;
                if (audio) {
                    audio.src = '';
                    audio.load(); // 重新加载音频元素，以清除播放器状态
                }
                // 重置文件输入元素
                this.$refs.directoryInput.value = '';
            },
            sendDirectoryPath() {
                // 发送用户输入的绝对路径到后端
                fetch('/convert-videos', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ directoryPath: this.directoryPath }),
                })
                    .then(response => response.json())
                    .then(data => {
                        console.log(data.message);
                    })
                    .catch(error => {
                        console.error('Error:', error);
                    });
            },
            convertVideoFormats() {
                // 可以在这里添加逻辑来打开输入框或者直接调用 sendDirectoryPath
                // 例如，直接调用 sendDirectoryPath：
                this.sendDirectoryPath();
            },
            selectDirectory() {
                this.$refs.directoryInput.click();
            },
            // 处理目录选择的方法
            handleDirectorySelected(event) {
                const files = event.target.files;
                if (files) {
                    const videoFiles = Array.from(files).filter(file => file.type.startsWith('video/')).slice(0, 6);
                    this.videoPaths = videoFiles.map(file => URL.createObjectURL(file));

                    // 查找音频文件
                    const audioFile = Array.from(files).find(file => file.type.startsWith('audio/wav'));
                    if (audioFile) {
                        this.audioPath = URL.createObjectURL(audioFile);
                    }
                }
            },


            // 新添加的方法，用于发送转换目录的绝对路径到后端
            sendConvertDirectoryPath() {
                // 发送用户输入的转换目录绝对路径到后端
                fetch('/convert-videos', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ directoryPath: this.convertDirectoryPath }),
                })
                    .then(response => response.json())
                    .then(data => {
                        console.log(data.message);
                        alert("转换完成")
                    })
                    .catch(error => {
                        console.error('Error:', error);
                    });
            }
        }
    });
</script>
</body>
</html>
